package com.heima.search.service.impl;

import com.heima.common.search.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.SearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;

    @Autowired
    private ApUserSearchService  searchService;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto==null || StringUtils.isEmpty(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String searchWords = dto.getSearchWords();
        Date minBehotTime = dto.getMinBehotTime();
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        //根据字符串查询
        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");
        //根据范围查询
        Map<String,Object> condition=new HashMap<>();
        condition.put("lt",minBehotTime.getTime());
        RangeQueryBuilder rangeQueryBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", condition);
        //布尔连接查询条件
        Map<String, AbstractQueryBuilder> map=new HashMap<>();
        map.put("must",stringQueryBuilder);
        map.put("filter",rangeQueryBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(map);
        //高亮查询
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color: red; font-size: inherit;'>", "</font>");


        SearchResponse search = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);
        searchService.insert(searchWords, AppThreadLocalUtil.getUser().getId());

        SearchHit[] hits = search.getHits().getHits();
        if (ArrayUtils.isEmpty(hits)){
            return ResponseResult.okResult("");
        }
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            if (hit==null){
                continue;
            }
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            // 处理高亮显示
            if (!CollectionUtils.isEmpty(highlightFields)) {
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title", join);
            } else {
                sourceAsMap.put("h_title", sourceAsMap.get("title"));
            }

            list.add(sourceAsMap);

        }
        return ResponseResult.okResult(list);
    }
}
